﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ViCode_LeVi.Data;
using ViCode_LeVi.Controls;
using ViCode_LeVi.Utilities;
using FES.Intimex.Client.Shared.Splash;
using ViCode_LeVi.KeyGen;

namespace ViCode_LeVi
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            ProjectData.Action_FileSave_Changed = (s) =>
                {
                    this.Title = s;
                };
            this.Loaded += new RoutedEventHandler(Window1_Loaded);
            this.Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing);
        }

        void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (System.IO.File.Exists(ProjectData.FileSave))
            {
                string s = "Do you want to save this Project?";
                var check = MessageBox.Show(s, "Warning", MessageBoxButton.YesNoCancel);
                if (check == MessageBoxResult.Yes)
                {
                    ProjectData.Intance.Save();
                    return;
                }
                if (check == MessageBoxResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }
        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            Splasher.CloseSplash();
            this.Hide();
            KeyGenHelper.CheckKey();
            this.Show();

            //MenuItem_Lang.DataContext = Langs.LangManager.Intance;
            //Set last
            var data = ProjectData.CreateDefaultRootData();
            ProjectData.Intance = data;
            SetDataContext();
            //DockPanel_Content.DataContextChanged += new DependencyPropertyChangedEventHandler(DockPanel_Content_DataContextChanged);
            //DockPanel_Content.DataContext = TabItem_Step1.DataContext = data.Steps[0];
            SetupHotkey();
        }

        private void SetupHotkey()
        {
            this.PreviewKeyUp += new KeyEventHandler(Window1_PreviewKeyUp);
        }

        void Window1_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (System.Windows.Input.Keyboard.Modifiers == System.Windows.Input.ModifierKeys.Control)
            {
                if (e.Key == Key.O)
                    MenuItem_Open_Click(null, null);
                else if (e.Key == Key.N)
                    MenuItem_New_Click(null, null);
                else if (e.Key == Key.S)
                    MenuItem_Save_Click(null, null);
                else if (e.Key == Key.E)
                    MenuItem_Quit_Click(null, null);
                else if (e.Key == Key.M)
                    MenuItem_DesignMode_Click(null, null);
                else if (e.Key == Key.I)
                    MenuItem_DesignRiskInfo_Click(null, null);
            }
            else
            {
                if (System.Windows.Input.Keyboard.Modifiers == System.Windows.Input.ModifierKeys.Control
                    &&
                    System.Windows.Input.Keyboard.Modifiers == System.Windows.Input.ModifierKeys.Shift)
                {
                    if (e.Key == Key.A)
                        MenuItem_SaveAs_Click(null, null);                    
                }
                else
                    if (e.Key == Key.F1)
                    {
                        MenuItem_HelpIndex_Click(null, null);
                    }
            }
        }

        void DockPanel_Content_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            //Panel tabItem = sender as Panel;
            //if(tabItem != null)
            //{
            //    var stepInfo = tabItem.DataContext as StepInfo;
            //    if(stepInfo != null)
            //    {
            //        VMTabControl_VMQuestionAnswer tab = new VMTabControl_VMQuestionAnswer();
            //        tabItem.Children.Add(tab);
            //        tab.SetupDataContext(stepInfo.QuestionAnwserGroups);                     
            //    }
            //}     
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {

        }

        private void MenuItem_Save_Click(object sender, RoutedEventArgs e)
        {
            LostFocus4UpdateBinding();
            //RootData root = TabControl_Root.DataContext as RootData;
            //root.Save();
            ProjectData.Intance.Save();
        }

        private void MenuItem_SaveAs_Click(object sender, RoutedEventArgs e)
        {
            LostFocus4UpdateBinding();
            //RootData root = TabControl_Root.DataContext as RootData;
            //root.SaveAs();
            ProjectData.Intance.SaveAs();
        }

        private void MenuItem_Open_Click(object sender, RoutedEventArgs e)
        {
            MenuItem_DesignMode.IsChecked = false;
            MenuItem_DesignMode_Click(null, null);

            ProjectData.OPenAndSetRootData();
            SetDataContext(); RefreshUI();
        }

        private void SetDataContext()
        {
            MenuItem_Operation.DataContext = null;
            MenuItem_Operation.DataContext = RootData.Intance;

            TabControl_Root.DataContext = null;
            TabControl_Root.DataContext = RootData.Intance;

            if (RootData.Intance != null)
            {
                ShowWindowMeasureAlert();
                RootData.Intance.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(Intance_PropertyChanged);
                RootData.Intance.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Intance_PropertyChanged);
            }
            TabControl_Root.SelectionChanged -= new SelectionChangedEventHandler(TabControl_Root_SelectionChanged);
            TabControl_Root.SelectionChanged += new SelectionChangedEventHandler(TabControl_Root_SelectionChanged);
            //this.DataContext = null;
            //this.DataContext = RootData.Intance;

            //Lui
            //for (int i = 0; i < TabControl_Root.Items.Count; i++)
            //{

            //    var tabItem = TabControl_Root.Items[i] as TabItem;
            //    UpdateBindingDataContext.UpdateDataContext(tabItem);

            //    if (tabItem.Content != null)
            //    {
            //        var vmrefreshs = DependencyHelper.GetVisualOfType<FrameworkElement>(tabItem.Content as FrameworkElement).ToArray();
            //        foreach (var vmr in vmrefreshs)
            //        {
            //            if (vmr is IVMRefresh)
            //                ((IVMRefresh)vmr).VMRefresh();
            //        }
            //    }
            //}
        }
        private void ShowWindowMeasureAlert()
        {
            if (RootData.Intance != null)
            {
                if (RootData.Intance.Step_Measure_Intance != null)
                {
                    var Measure = RootData.Intance.Step_Measure_Intance;
                    if (Measure.Measurements_Source != null && Measure.Measurements_Source.Count > 0)
                    {
                        List<Step_Measurement_Item> MeasurementDetailNeedAlert = new List<Step_Measurement_Item>();
                        foreach (var item in Measure.Measurements_Source)
                        {
                            DateTime DayNeedAlert = item.EndDate.AddDays(-RootData.DAYS_ALERT_MEASURE);
                            if (DayNeedAlert.Date <= DateTime.Today && item.Status != "Finished")
                            {
                                MeasurementDetailNeedAlert.Add(item);
                            }
                        }
                        if (MeasurementDetailNeedAlert.Count > 0)
                        {
                            WindowMeasureAlert win = new WindowMeasureAlert();
                            win.MeasurementDetailNeedAlert = MeasurementDetailNeedAlert.ToArray();
                            win.SetItemsSource();
                            win.Show();
                        }

                    }
                }
            }
        }
        void TabControl_Root_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (RootData.Intance != null)
            {
                RootData.Intance.Step_Current = TabControl_Root.SelectedItem == null ? null : ((TabItem)TabControl_Root.SelectedItem).DataContext as StepInfo;
            }
        }

        void Intance_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Step_Current")
            {
                var step = TabControl_Root.Items.Cast<TabItem>().FirstOrDefault(c => c.DataContext == RootData.Intance.Step_Current);
                if (step != null)
                    TabControl_Root.SelectedItem = step;
            }
        }
        private void LostFocus4UpdateBinding()
        {
            var tabItem = TabControl_Root.SelectedItem as TabItem;
            TabItem_Step1.Focus();
            if (tabItem != null)
                tabItem.Focus();
        }
        public void RefreshUI()
        {
            TabControl_Root.UpdateLayout();
            TabItem_Step1.UpdateLayout();
            TabItem_Step2.UpdateLayout();
            TabItem_Step3.UpdateLayout();
            TabItem_Step4.UpdateLayout();
            VMTabHeaders.Refresh();
            VMTextBlockExt_ControlTextInfoInDatas.RefreshUI();
            CommandManager.InvalidateRequerySuggested();

            //Color
            var listText = DependencyHelper.GetVisualOfType<VMTextBox>(this);
            if (listText != null)
            {
                foreach (var txt in listText)
                    txt.RefreshFormat();
            }
        }
        private void ShowProjectInfo()
        {
            VMProjectInfo project = new VMProjectInfo() { DataContext = ProjectData.Intance };
            Window w = new Window()
            {
                Icon = Application.Current.MainWindow.Icon,
                Content = project
                    ,
                SizeToContent = SizeToContent.Height
                ,
                Title = "Project Info"
                ,
                WindowState = WindowState.Normal
                    ,
                WindowStartupLocation = WindowStartupLocation.CenterScreen
                    //,Height = System.Windows.SystemParameters.PrimaryScreenHeight * 8 / 9
                ,
                Width = System.Windows.SystemParameters.PrimaryScreenWidth * 4 / 9
            };
            //w.Width =
            w.ShowDialog();
        }
        private void MenuItem_New_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Do you want to save current project?", "Please", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) == MessageBoxResult.Yes)
            {
                ShowProjectInfo();
                MenuItem_Save_Click(null, null);
            }
            else
            {
                ShowProjectInfo();
            }
            ProjectData.FileSave = string.Empty;
            ProjectData.Intance = ProjectData.CreateDefaultRootData();
            SetDataContext();
        }

        private void MenuItem_DesignMode_Click(object sender, RoutedEventArgs e)
        {
            VMTextBlockExt.IsInDesignMode = MenuItem_DesignMode.IsChecked;
        }
        private void MenuItem_DesignRiskInfo_Click(object sender, RoutedEventArgs e)
        {
            WindowEditInfo frm = new WindowEditInfo();
            frm.Show();
        }
        private void MenuItem_Quit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void MenuItem_HelpIndex_Click(object sender, RoutedEventArgs e)
        {
            string sPath = FileFolder.AppInfo.AppDirectory + "/help.chm";
            FileFolder.RunFileHelper.RunFile(sPath);
        }

        private void MenuItem_AboutUs_Click(object sender, RoutedEventArgs e)
        {
            FES.Intimex.Client.Shared.Splash.Splasher.ShowSplash();
        }

        private void MenuItem_ProjectInfo_Click(object sender, RoutedEventArgs e)
        {
            ShowProjectInfo();
        }

        private void MenuItem_CloseProject_Click(object sender, RoutedEventArgs e)
        {
            MenuItem_Save_Click(null, null);
            TabControl_Root.SelectedIndex = 0;
            MenuItem_New_Click(null, null);
        }
    }
}
